﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Collections.Specialized;
using System.ServiceModel;

using BSC;
using EmrDatastructure;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using EmrLogger;
using System.Data.Entity;


namespace EmrDAL
{
    public partial class EmrService : IEmrService
    {
        public virtual void CreateEmrDemographic(EmrDemographic r)
        {
            try
            {
                using (var context = new EmrContext())
                {
                    context.Demographics.Add(r);
                    context.SaveChanges();
                }
            }
            catch (DbEntityValidationException ex)
            {
                foreach (var failure in ex.EntityValidationErrors)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("{0} failed validation", failure.Entry.Entity.GetType()));
                    foreach (var error in failure.ValidationErrors)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("- {0} : {1}", error.PropertyName, error.ErrorMessage));
                    }
                }
                LogAndThrow.Log("Error CreateEmrDemographic Validation", ex);
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error CreateEmrDemographic exception", ex);
            }
        }
        public virtual EmrDemographic ReadEmrDemographic(string id)
        {
            try
            {
                using (var context = new EmrContext())
                {
                    return context.Demographics.Find(id);
                }
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error ReadEmrDemographic", ex);
                return null;
            }
        }
        public virtual void UpdateEmrDemographic(EmrDemographic r)
        {
            try
            {
                using (var context = new EmrContext())
                {
                    context.Demographics.Attach(r);
                    context.Entry(r).State = EntityState.Modified;
                    int recordsAffected = context.SaveChanges();
                }
            }
            catch (DbUpdateConcurrencyException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                LogAndThrow.Log("Error UpdateEmrDemographic Concurrency", ex);
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error UpdateEmrDemographic", ex);
            }
        }
        public virtual void DeleteEmrDemographic(string emrDemographicId)
        {
            try
            {
                using (var context = new EmrContext())
                {
                    EmrDemographic ed = context.Demographics.Find(emrDemographicId);
                    if (ed != null)
                    {
                        //context.Demographics.Remove(context.Demographics.Find(emrDemographicId));
                        context.Demographics.Remove(ed);
                        int recordsAffected = context.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error DeleteEmrDemographic", ex);
            }
        }

        public virtual IList<EmrDemographic> SearchList(string orLastName, string orFirstName, DateTime? orDateOfBirth)
        {
            string search = "";
            int searchParamsCount = 0;
            if (orLastName != null)
            {
                search = " LastName=@LastName";
                searchParamsCount++;
            }
            if (orFirstName != null)
            {
                searchParamsCount++;
                if (string.IsNullOrEmpty(search))
                {
                    search = " FirstName=@FirstName";
                }
                else
                {
                    search += " OR FirstName=@FirstName";
                }
            }
            if (orDateOfBirth != null)
            {
                searchParamsCount++;
                if (string.IsNullOrEmpty(search))
                {
                    search = " DateOfBirth=@DateOfBirth";
                }
                else
                {
                    search += " OR DateOfBirth=@DateOfBirth";
                }
            }
            try
            {
                Database.SetInitializer(new EmrContextInitializerIfNotExists());
                using (var context = new EmrContext())
                {
                    SqlParameter[] sqlParameters = new SqlParameter[searchParamsCount];
                    if (orLastName != null)
                    {
                        sqlParameters[--searchParamsCount] = new SqlParameter("@LastName", orLastName);
                    }
                    if (orFirstName != null)
                    {
                        sqlParameters[--searchParamsCount] = new SqlParameter("@FirstName", orFirstName);
                    }
                    if (orDateOfBirth != null)
                    {
                        sqlParameters[--searchParamsCount] = new SqlParameter("@DateOfBirth", orDateOfBirth);
                    }
                    List<EmrDemographic> recs = null;
                    if (string.IsNullOrEmpty(search))
                    {
                        recs = context.Demographics.SqlQuery("select * from EmrDemographics", sqlParameters).ToList();
                    }
                    else
                    {
                        recs = context.Demographics.SqlQuery("select * from EmrDemographics WHERE " + search, sqlParameters).ToList();
                    }
                    return recs;
                }
            }
            catch (Exception ex)
            {
                LogAndThrow.Log("Error SearchList", ex);
                return null;
            }
        }

        // probably limit by hospital, doctor or some other way
        // Hospital AND lastName  -- Not by OR ??
        // Pass in a List of Name,Value pair -- the value needs to be object. NameValueCollection is string-string
        // array of ors (“CustId=3451”);
        public virtual IList<EmrDemographic> ReadListEmrDemographic(string howToSpec)
        {
            return new List<EmrDemographic>();
        }
    }
}
